#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>

#define NUM 16

//const char *myfile = "/home/yxj/Linux/gitcode1/linux/lesson17/mycmd";
const char *myfile = "./mycmd";

int main(int argc,char *argv[], char *env[])
{
    //为什么我要创建子进程？
    //为了不影响父进程，为什么不想影响父进程呢？
    //因为我们想让父进程聚焦在读取数据，解析数据，指派进程代码的功能
    //如果不创建物品们替换的进程只能是父进程，如果创建了，替换的进程就是子进程，而不影响父进程(为什么？)
    //while(1)
    //{
        //1.显示一个提示行：root@localhost#
        //2.获取用户输入的字符串，fgets,scanf  --> ls -a -l
        //3.对字符串进行解析
        //4.下面的代码
        
    //全局变量具有全局性，可以被子进程继承下去
    char *const _env[NUM] = {
       (char*)"111VAL=1200000000000003",
        NULL
    }; 
        pid_t id = fork();
        if(id == 0)
        {
            //子进程
            //ls -a -l
            printf("子进程开始运行,pid:%d\n",getpid());
            sleep(3);
            char *const _argv[NUM] = {
               (char*)"ls",
               (char*)"-a",
               (char*)"-l",
               (char*)"-i",
                NULL};
            execle(myfile,"mycmd","-a",NULL,env);
            //execlp("./test.py","test.py",NULL);
            //execlp("python","python","test.py",NULL);
            //execlp("bash","bash","test.sh",NULL);
            //execl(myfile,"mycmd","-b",NULL);
            //execl("/usr/bin/ls","ls","-a","-l",NULL);
            //execv("/usr/bin/ls",_argv);//和上面的execl只有传参方式的区别
            //execlp("ls","ls","-a","-l",NULL);
            //execvp("ls",_argv);
            exit(1);
        }
        else 
        {
            //父进程
            printf("父进程开始运行,pid:%d\n",getpid());
            int status = 0;
            pid_t id = waitpid(-1,&status,0);//阻塞等待,一定是子进程先运行完毕，然后父进程获取之后，才退出
            if(id >0)
            {
                printf("wait success,exit code:%d\n",WEXITSTATUS(status));
            }
        }   
    
    //} end while 
}
